#include "internetserver.h"

InternetServer::InternetServer()
{
    temperature = 0;
    MFS = 0;
    dust_density = 0;
    humidity = 0;
}

InternetServer::~InternetServer()
{
    sql.close();
}

InternetServer::InternetServer(const QHostAddress &address, quint16 port) {
    S_listen(address, port);
}

bool InternetServer::S_listen(const QHostAddress &address, quint16 port)
{
    // 开始监听指定端口
    if (server.listen(address, port)) {
        qDebug() << "正在监听端口："<<port<<Qt::endl;
    } else {
        qDebug() << "Failed to start listening: " << server.errorString();
        return false;
    }
    return true;
}

void InternetServer::S_connect()
{
    // 当有客户端连接时接受连接请求并处理
    QObject::connect(&server, &QTcpServer::newConnection, [&]() {
        socket = server.nextPendingConnection();//返回当前链接的SOCKTET
        if (socket!= nullptr) {
            qDebug() << "有客户端连接成功.";
            connect(socket, &QTcpSocket::readyRead, this, &InternetServer::onReadyRead);
            connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
        }
            });
    if(sql.open("data") == false)
    {
        QString str = "CREATE DATABASE data";
        sql.exec(str);
        qDebug()<<"创建了数据库"<<Qt::endl;
    }
    QString str1 = "CREATE TABLE IF NOT EXISTS data ("
                   "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                   "time DATETIME,"
                   "temperature FLOAT(6,3),"
                   "humidity FLOAT(6,3),"
                   "dust_density FLOAT(6,3),"
                   "MFS FLOAT(6,3))";
    sql.exec(str1);
}


void InternetServer::onReadyRead()
{
    buffer = socket->readAll();//从底层把接收的字节全部读取出来
    QByteArray floatData = buffer.left(sizeof(database));
    memcpy(&d, floatData.data(), sizeof(database));
    // 获取当前的日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString dateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
    //将数据写入数据库
    QString str = "INSERT INTO data (time, temperature, humidity, dust_density, MFS) VALUES ('%1', '%2', '%3', %4, %5);";
    sql.exec(str.arg(dateTimeString).arg(d.temperature).arg(d.humidity).arg(d.dust_density).arg(d.MFS));
    this->temperature = d.temperature;
    this->MFS = d.MFS;
    this->dust_density = d.dust_density;
    this->humidity = d.humidity;
    pMainWindow->setArg(temperature, MFS, dust_density, humidity, currentDateTime);
    qDebug() << "收到的浮点数为3" << d.MFS << d.dust_density << d.humidity << d.temperature;
}


void InternetServer::setMainWindow(MainWindow *pMainWindow)
{
    this->pMainWindow = pMainWindow;
    pMainWindow->setArg(temperature, MFS, dust_density, humidity,currentDateTime);
}

